package com.ruoyi.framework.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.DataCustom;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.PermissionContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class DataCustomAspect
{
    /**
     * 客户数据过滤关键字
     */
    public static final String DATA_CUSTOM = "dataCustom";

    private static Logger logger = LoggerFactory.getLogger(DataCustomAspect.class);

    @Before("@annotation(controllerDataCustom)")
    public void doBefore(JoinPoint point, DataCustom controllerDataCustom) throws Throwable
    {
        clearDataCustom(point);
        handleDataCustom(point, controllerDataCustom);
    }

    protected void handleDataCustom(final JoinPoint joinPoint, DataCustom controllerDataCustom)
    {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
            {
                String permission = StringUtils.defaultIfEmpty(controllerDataCustom.permission(), PermissionContextHolder.getContext());
                dataScopeFilter(joinPoint, currentUser, controllerDataCustom.customAlias(),
                        controllerDataCustom.userAlias(), permission);
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user 用户
     * @param customAlias 客户别名
     * @param userAlias 用户别名
     * @param permission 权限字符
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String customAlias, String userAlias, String permission)
    {
        StringBuilder customString = new StringBuilder();
        //logger.debug("ZZZ " + "user = " + user);
        //logger.debug("ZZZ " + "permission = " + permission);

        for (String custom : user.getCustoms())
        {
            customString.append(',');
            customString.append('\'' + custom + '\'');
        }

        if (StringUtils.isNotBlank(customString.toString()))
        {
            //logger.debug("ZZZ " + "customString = " + customString);

            Object params = joinPoint.getArgs()[0];
            //logger.debug("ZZZ " + "params = " + params);
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
            {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_CUSTOM, customString.substring(1));
                //logger.debug("ZZZ " + "baseEntity = " + baseEntity);
                //logger.debug("ZZZ " + "baseEntity.getParams() = " + baseEntity.getParams().toString());
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.customScope参数防止注入
     */
    private void clearDataCustom(final JoinPoint joinPoint)
    {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
        {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_CUSTOM, "");
        }
    }
}
